Subscribing to Multiple Observables in Angular Components

您所在的位置:网站首页 multiple different Subscribing to Multiple Observables in Angular Components

Subscribing to Multiple Observables in Angular Components

2024-07-16 23:43:37| 来源: 网络整理| 查看: 265

Angular applications heavily rely on RxJS Observables. While building large front end apps with these technologies we quickly will need to learn how to manage subscribing to multiple Observables in our components. In this post we are going to cover five different ways to subscribe to multiple Observables and the pros and cons of each.

In our component, we will have three Observables. Each Observable has slightly different behavior. The first Observable emits a single value immediately. The second Observable emits a single value after a couple of seconds. The third Observable emits multiple values one value every second. Below are some functions that return the Observables that we will use in our components.

import { Observable, of, interval } from 'rxjs';import { delay } from 'rxjs/operators';

export function getSingleValueObservable() { return of('single value');}

export function getDelayedValueObservable() { return of('delayed value').pipe(delay(2000));}

export function getMultiValueObservable() { return new Observable(observer => { let count = 0; const interval = setInterval(() => { observer.next(count++); console.log('interval fired'); }, 1000);

return () => { clearInterval(interval); }; });}

Manual Subscriptions

Let's take a look at our component TypeScript to see our multiple Observables used with our first technique of subscribing directly to our component.

import { Component } from '@angular/core';import { Observable, Subscription } from 'rxjs';

import { getSingleValueObservable, getDelayedValueObservable, getMultiValueObservable} from './../util';

@Component({ selector: 'app-manual-subscriptions', template: `

{{first}}

{{second}}

{{third}}

`})export class ManualSubscriptionsComponent { first: string; second: string; third: number; thirdSubscription: Subscription;

ngOnInit() { getSingleValueObservable() .subscribe(value => this.first = value);

getDelayedValueObservable() .subscribe(value => this.second = value);

this.thirdSubscription = getMultiValueObservable() .subscribe(value => this.third = value); }

// Multi value observables must manually // unsubscribe to prevent memory leaks. ngOnDestroy() { this.thirdSubscription.unsubscribe(); }}

In this component we simply call .subscribe() to get the events from our Observables. When first working with Angular and RxJS subscribing directly to the Observable is where most users start.

The pros to this are it's simple and works well for single values. The cons to this are if our Observable has multiple values we must manually unsubscribe with ngOnDestroy life cycle hook. If we don't unsubscribe from an Observable when the component is destroyed, we will leave memory leaks. If you remove the .unsubscribe() in the working demo, you will see this behavior when the *ngIf removes the component. In our later examples, we will see how Angular can help us manage our Rx subscriptions.

Async Pipe

In this next example, we will see how Angular has a built-in template syntax that cleans up our prior component quite a bit. With Angular, we can use the async pipe feature. The Async pipe will allow us to let angular know what properties on our component are Observables so it can automatically subscribe and unsubscribe to our component for us. Let's take a look at the component.

import { Component } from '@angular/core';

import { getSingleValueObservable, getDelayedValueObservable, getMultiValueObservable} from './../util';

@Component({ selector: 'app-async-pipe', templateUrl: './async-pipe.component.html'})export class AsyncPipeComponent { show = false; first$ = getSingleValueObservable(); second$ = getDelayedValueObservable(); third$ = getMultiValueObservable();}

As you can see our component, we directly assign the result of our function to the properties of our component. Our Observables are using the convention to end with a $ to help distinguish what is an Observable vs. a primitive for learning purposes.

Async Pipe

Toggle

{{first$ | async}} {{second$ | async}} multi values {{third$ | async}}

As we can see in our template, the async pipe automatically subscribes and handles our Observables. The pros to this are we can let Angular do the heavy lifting to our Observables. The cons are that this syntax become a bit more complicated when we have multiple subscriptions. In a later step, we will see how we can improve on this.

ForkJoin and *ngIf

Sometimes we need to subscribe to multiple Observables at once. A typical scenario is when using multiple HTTP requests. In this example, we will use the RxJS operator ForkJoin.

import { Component, OnInit } from '@angular/core';import { forkJoin } from 'rxjs';import { map } from 'rxjs/operators';

import { getSingleValueObservable, getDelayedValueObservable, getMultiValueObservable} from './../util';

@Component({ selector: 'app-fork-join-operator', templateUrl: './fork-join-operator.component.html'})export class ForkJoinOperatorComponent { show = false; values$ = forkJoin( getSingleValueObservable(), getDelayedValueObservable() // getMultiValueObservable(), forkJoin on works for observables that complete ).pipe( map(([first, second]) => { // forkJoin returns an array of values, here we map those values to an object return { first, second }; }) );}

In our component, we use forkJoin to combine the Observables into a single value Observable. The forkJoin operator will subscribe to each Observable passed into it. Once it receives a value from all the Observables, it will emit a new value with the combined values of each Observable. ForkJoin works well for single value Observables like Angular HttpClient. ForkJoin can be comparable to Promise.All().

forkJoin Operator

Toggle

{{values.first}} {{values.second}} {{values.third}}

In our template, we are going to leverage a few Angular template features to handle our Observables. First, our ng-container allows us to use Angular directives like *ngIf without generating HTML like excessive div elements. Next, we use a *ngIf feature that allows us to subscribe with the async pipe and then assign the value from the Observable into a temporary template variable that we can reuse in our template, so we don't have to repeat the async pipe syntax multiple times.

If you take note with the ForkJoin, we don't get any values rendered until all Observables pass back a value. In our working demo, we don't see any values until the delayed Observable emits its value. This technique allows us to clean up our template by subscribing once letting Angular handle our subscription while referencing our Observable multiple times. The issue we see here is that forkJoin limits us to single value Observables only. The next example we will see how to handle multi-value Observables.

Combine Latest and *ngIf

This example will use an operator called combineLatest this is similar to forkJoin but allows Observables with multiple values. Let's take a look at the component TypeScript.

import { Component, OnInit } from '@angular/core';import { combineLatest } from 'rxjs';import { map } from 'rxjs/operators';

import { getSingleValueObservable, getDelayedValueObservable, getMultiValueObservable} from './../util';

@Component({ selector: 'app-combine-latest-operator', templateUrl: './combine-latest-operator.component.html'})export class CombineLatestOperatorComponent { show = false; values$ = combineLatest( getSingleValueObservable(), getDelayedValueObservable(), getMultiValueObservable() ).pipe( map(([first, second, third]) => { // combineLatest returns an array of values, here we map those values to an object return { first, second, third }; }) );}

As we can see combineLatest is very similar to forkJoin. Combine Latest will emit the single combined value as soon as at least every Observable emits a single value and will continue emitting multiple values with the latest of each.

combineLatest Operator

Toggle

{{values.first}} {{values.second}} {{values.third}}

In the template, we use the same technique with *ngIf and the async pipe. Next, let's look at a use case of where we want to subscribe to multiple different Observables without the use of forkJoin or combineLatest.

Subscribing with Async Pipe Objects

In this example, we will use the Async pipe but show how we can subscribe to multiple Observables in the template instead of the component TypeScript.

import { Component } from '@angular/core';

import { getSingleValueObservable, getDelayedValueObservable, getMultiValueObservable} from './../util';

@Component({ selector: 'app-async-pipe-object', templateUrl: './async-pipe-object.component.html'})export class AsyncPipeObjectComponent { show = false; first$ = getSingleValueObservable(); second$ = getDelayedValueObservable(); third$ = getMultiValueObservable();}

Our component TypeScript is similar to our earlier examples. The template is where things get interesting.

Async Pipe ObjectToggle

{{values.first}} {{values.second}} multi values {{values.third}}

Using *ngIf and the async pipe we can unwrap each Observable into a single value object that contains the unwrapped value of each Observable. This use of *ngIf is not a well-known ability of the Angular template syntax but allows an easy way to subscribe to multiple Observables in our template as well as reference to it numerous times.

As we can see, there are many ways to subscribe to Observables in Angular each with pros and cons. Take a look at the working demos below!



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭